package com.mdp.workflow.bus.listener.global;

import com.mdp.core.SpringUtils;
import com.mdp.workflow.biz.ru.service.ProcinstNodeInfoService;
import com.mdp.workflow.cfg.FlowableListenerConfig;
import com.mdp.workflow.comm.dict.ProcinstConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 任务节点前置监听处理类,由于启动后马上进入第一个审批节点，如果第一个审批节点创建不成功，会导致整个流程启动不成功，而此事件是在第一个任务节点创建前执行，因此涉及事务性的远程调用不能在此事件中执行。
 * 拿不到变量，此类没什么用,启动事件放在  ExecutionServiceImpl.start进行推送
 * @author: chenyc
 * @create: 2019-05-04 20:51
 **/
@Component
public class ProcessStartedListener implements FlowableEventListener {
	
	Log log=LogFactory.getLog(ProcessStartedListener.class);

	
	@Autowired
	private ProcinstNodeInfoService procinstNodeInfoService;
	 
	 public DelegateExecution getExecution(String executionId) {
	        if (executionId != null) {
	            CommandContext commandContext = CommandContextUtil.getCommandContext();
	            if (commandContext != null) {
	                return CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId);
	            }
	        }
	        return null;
	    }
    @Override
    public void onEvent(FlowableEvent event) {
		if(FlowableListenerConfig.PROCESS_STARTED.equals(event.getType().name())) {
        		FlowableEntityEventImpl exec=((FlowableEntityEventImpl) event);  
	            
	            //调用其它远程服务 
	            ExecutionEntityImpl exeEntity = (ExecutionEntityImpl) exec.getEntity();
	            TaskService ts=SpringUtils.getBean(TaskService.class);
	            Map<String,Object> flowVars=exeEntity.getVariables(); 
	            String currentUsername=(String) flowVars.get(ProcinstConstants.CURR_USERNAME);
	            ts.addComment(null, exeEntity.getProcessInstanceId(), currentUsername+"发起流程");
	            
		}
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}